<template>
  <el-dialog
    class="subscribeOpen"
    :visible.sync="visible"
    :title="title"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="dataForm"
      label-position="right"
      label-width="80px"
      style="width: 480px; margin-left: 50px;"
    >
      <el-form-item label="日期" prop="warehouseAdjustmentTime">
        <el-date-picker
          size="small"
          v-model="dataForm.warehouseAdjustmentTime"
          type="date"
          @change="timeChange"
          value-format="yyyy-MM-dd"
          style="width: 400px;"
          placeholder="请选择成立至上一交易日"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="净值" prop="warehouseAdjustmentNetworth">
        <el-input
          @change="checkInitAmount('warehouseAdjustmentNetworth')"
          v-model="dataForm.warehouseAdjustmentNetworth"
          placeholder="请输入买入的净值"
        />
      </el-form-item>
      <el-form-item label="金额" prop="warehouseAdjustmentEquity">
        <el-input
          @change="checkInitAmount('warehouseAdjustmentEquity')"
          v-model="dataForm.warehouseAdjustmentEquity"
          placeholder="请输入买入的金额"
        >
          <template slot="append" style="width: 80px;">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="份额" prop="warehouseAdjustmentShare">
        <el-input
          @change="checkInitAmount('warehouseAdjustmentShare')"
          v-model="dataForm.warehouseAdjustmentShare"
          placeholder="请输入买入的份额"
        >
          <template slot="append" style="width: 80px;">份</template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="isSubscribe == 2">
        <span class="tip">可卖出份额：{{ share }}份</span>
        <span class="sellOutAll" @click="sellOutAll">全部卖出</span>
      </el-form-item>
      <div v-if="isSubscribe == 1">
        <el-form-item label="认/申购费" prop="subscriptionFee">
          <el-input v-model="dataForm.subscriptionFee" placeholder="请输入">
            <template slot="append" style="width: 80px;">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="管理费" prop="managementFee">
          <el-input v-model="dataForm.managementFee" placeholder="请输入">
            <template slot="append" style="width: 80px;">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="业绩报酬" prop="performanceFee">
          <el-input v-model="dataForm.performanceFee" placeholder="请输入">
            <template slot="append" style="width: 80px;">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="佣金比例" prop="commissionRate">
          <el-input v-model="dataForm.commissionRate" placeholder="请输入">
            <template slot="append" style="width: 80px;">%</template>
          </el-input>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  purchaseOrBuyback,
  queryAvailableShare,
  findNetWorthByStratrgyIdAndDate,
  queryCompositionNetworthByCompositionIdAndDate,
} from '@/api/afterInvest'
import { mapGetters } from 'vuex'
import { downFixed } from '@/utils'

export default {
  data() {
    return {
      visible: false,
      isSubscribe: 1,
      title: '',
      share: 0,
      dataForm: {
        warehouseAdjustmentTime: null,
        warehouseAdjustmentNetworth: '',
        warehouseAdjustmentEquity: '',
        warehouseAdjustmentShare: '',
        warehouseAdjustmentName: '',
        subscriptionFee: '',
        managementFee: '',
        performanceFee: '',
        commissionRate: '',
      },
      rules: {
        warehouseAdjustmentTime: [
          { required: true, message: '日期必填', trigger: 'change' },
        ],
        warehouseAdjustmentNetworth: [
          { required: true, message: '净值必填', trigger: 'change' },
        ],
        warehouseAdjustmentEquity: [
          { required: true, message: '金额必填', trigger: 'change' },
        ],
        warehouseAdjustmentShare: [
          { required: true, message: '份额必填', trigger: 'change' },
        ],
      },
    }
  },
  computed: {
    ...mapGetters(['userId']),
  },
  methods: {
    checkInitAmount(key) {
      this.$set(
        this.dataForm,
        key,
        downFixed(this.checkNumber(this.dataForm[key]), 2),
      )
      switch (key) {
        case 'warehouseAdjustmentEquity':
          this.dataForm.warehouseAdjustmentShare = downFixed(
            this.checkNumber(
              this.dataForm.warehouseAdjustmentEquity /
                this.dataForm.warehouseAdjustmentNetworth,
            ),
            2,
          )
          break
        case 'warehouseAdjustmentShare':
          this.dataForm.warehouseAdjustmentEquity = downFixed(
            this.checkNumber(
              this.dataForm.warehouseAdjustmentShare *
                this.dataForm.warehouseAdjustmentNetworth,
            ),
            2,
          )
          break
        case 'warehouseAdjustmentNetworth':
          this.dataForm.warehouseAdjustmentShare = downFixed(
            this.checkNumber(
              this.dataForm.warehouseAdjustmentEquity /
                this.dataForm.warehouseAdjustmentNetworth,
            ),
            2,
          )
          break

        default:
          break
      }
    },
    // 过滤非数字
    checkNumber(value) {
      value = value.toString()
      value = value.replace(/[^\d.]/g, '')
      value = value.replace(/^\./g, '')
      value = value.replace(/\.{2,}/g, '.')
      value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      return +value
    },
    init(id, name, isSubscribe, type) {
      this.isSubscribe = isSubscribe
      this.visible = true
      this.title = isSubscribe == 1 ? `申购/入金-${name}` : `赎回/出金-${name}`
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.dataForm.warehouseAdjustmentName = name
        this.dataForm.warehouseAdjustmentId = id
        this.dataForm.warehouseAdjustmentType = type
        this.dataForm.warehouseAdjustmentDirect = isSubscribe - 1
        if (isSubscribe == 2) this.getInfo()
      })
    },
    timeChange() {
      if (this.dataForm.warehouseAdjustmentType === 0) {
        queryCompositionNetworthByCompositionIdAndDate({
          id: this.dataForm.warehouseAdjustmentId,
          networthTime: this.dataForm.warehouseAdjustmentTime,
        }).then((res) => {
          if (!res.networthValue) {
            this.$message({
              type: 'info',
              message: '当天净值数据缺失，请手动填写',
              duration: 2000,
            })
          }
          this.dataForm.warehouseAdjustmentNetworth = res.networthValue
          console.log('净值', res.networthValue)
        })
      } else {
        findNetWorthByStratrgyIdAndDate({
          id: this.dataForm.warehouseAdjustmentId,
          networthTime: this.dataForm.warehouseAdjustmentTime,
        }).then((res) => {
          if (!res.networthValue) {
            this.$message({
              type: 'info',
              message: '当天净值数据缺失，请手动填写',
              duration: 2000,
            })
          }
          this.dataForm.warehouseAdjustmentNetworth = res.networthValue
          console.log('净值', res.networthValue)
        })
      }
    },
    sellOutAll() {
      this.dataForm.warehouseAdjustmentShare = this.share
      this.checkInitAmount('warehouseAdjustmentShare')
    },
    submit() {
      purchaseOrBuyback({
        ...this.dataForm,
        createUser: this.userId,
      }).then((res) => {
        this.$message({
          type: 'success',
          message: res.msg,
        })
        this.visible = false
        this.$emit('closeOpen')
      })
    },
    getInfo() {
      queryAvailableShare({
        id: this.dataForm.warehouseAdjustmentId,
        type: this.dataForm.warehouseAdjustmentType,
      }).then((res) => {
        console.log(66, res)
        this.share = res.body
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.subscribeOpen {
  ::v-deep .el-date-editor--date {
    position: relative;
    .el-input__inner {
      padding-left: 10px;
    }
    .el-input__prefix {
      transform: translateX(355px);
    }
  }
  ::v-deep .el-input-group__append {
    width: 60px;
    text-align: center;
    padding: 0;
  }
  .tip {
    color: #333333;
  }
  .sellOutAll {
    color: #1890ff;
    cursor: pointer;
    margin-left: 20px;
  }
}
</style>
